package com.jsgt.greekfire.common.widget

import android.content.Context
import android.text.InputFilter
import android.text.method.DigitsKeyListener
import android.util.AttributeSet
import androidx.appcompat.widget.AppCompatEditText


/**
 * author fhx
 * create time 2020/5/10 14:32
 **/
class NumberEditView constructor(context: Context, attrs: AttributeSet?, defStyleAttr: Int) :
    AppCompatEditText(context, attrs, defStyleAttr) {
    constructor(context: Context, attrs: AttributeSet?) : this(
        context,
        attrs,
        android.R.attr.editTextStyle
    )
    val POINTER = "."
    constructor(context: Context) : this(context, null, android.R.attr.editTextStyle)
    var numberDot = 2//几位小数
    init {
        keyListener = DigitsKeyListener.getInstance("1234567890.")
        val lengthFilter =
            InputFilter { source, start, end, dest, dstart, dend ->
                // source:当前输入的字符
                // start:输入字符的开始位置
                // end:输入字符的结束位置
                // dest：当前已显示的内容
                // dstart:当前光标开始位置
                // dent:当前光标结束位置
                if (dest.isEmpty() && source == POINTER) {
                    return@InputFilter "0."
                }
                if(dest.isEmpty() && source == "0"){
                    return@InputFilter "0."
                }
                if (dest.toString().contains(POINTER)) {
                    if (source.toString() == POINTER) {
                        return@InputFilter ""
                    }
                    if (dest!!.length - 1 - dest.toString().indexOf(POINTER) > numberDot-1) {
                        return@InputFilter ""
                    }
                }
                null
            }
        filters = arrayOf(lengthFilter, InputFilter.LengthFilter(18))
    }
}